package com.sagereal.wtc.factorymode.Activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.sagereal.wtc.factorymode.R;

public class VibrationActivity extends BaseActivity {
    private TextView mTestView;
    private Button mTestPass,mTestFail;
    private Vibrator mVibrator;
    private BroadcastReceiver mScreenReceiver;
    private PowerManager mPowerManager;
    private PowerManager.WakeLock wakeLock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vibration);
        setTitle(getString(R.string.title_vibration_test));

        mTestView = findViewById(R.id.viboration_notify);
        mTestPass = findViewById(R.id.test_pass);
        mTestFail = findViewById(R.id.test_fail);
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        // 初始化WakeLock
        wakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp::VibrationWakeLock");
        // 注册广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        mScreenReceiver = new ScreenReceiver();
        registerReceiver(mScreenReceiver, filter);

        // 检查设备是否支持振动
        if (mVibrator == null || !mVibrator.hasVibrator()) {
            mTestView.setText(getString(R.string.unviboration_notify));
//            Toast.makeText(this, getString(R.string.unviboration_notify), Toast.LENGTH_SHORT).show();
            mTestPass.setEnabled(false);
            //测试失败
            mTestFail.setOnClickListener(v -> {
                // 类似地发送Intent，但状态为"fail"
                Intent intent = new Intent(VibrationActivity.this, ItemTestActivity.class);
                intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1)); // 获取启动该Activity时传递的ItemId
                intent.putExtra("status", "fail");
                intent.putExtra("check", getIntent().getStringExtra("check"));
                setResult(RESULT_OK , intent);
                finish();
            });
        } else {
            initView();
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            // 获取唤醒锁并开始振动
            if (!wakeLock.isHeld()) {
                wakeLock.acquire();
            }
            startVibrating();
        } else {
            // 释放唤醒锁并停止振动
            if (wakeLock.isHeld()) {
                wakeLock.release();
            }
            stopVibrating();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        // 获取唤醒锁并开始振动
        if (!wakeLock.isHeld()) {
            wakeLock.acquire();
        }
        startVibrating();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 释放唤醒锁并停止振动
        if (wakeLock.isHeld()) {
            wakeLock.release();
        }
        stopVibrating();
    }

    //开始振动
    private void startVibrating() {
        if (mVibrator != null && mVibrator.hasVibrator()) {
            long[] pattern = {0, 1000, 1000}; // 振动模式：等待0ms，振动1000ms，静止1000ms
            mVibrator.vibrate(pattern, 0);
        }
    }

    //停止振动
    private void stopVibrating() {
        if (mVibrator != null) {
            mVibrator.cancel();
        }
    }

    // 屏幕状态广播接收器
    private class ScreenReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
                // 息屏，停止振动并释放唤醒锁
                stopVibrating();
                if (wakeLock.isHeld()) {
                    wakeLock.release();
                }
            } else if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
                // 亮屏，获取唤醒锁并开始振动
                if (!wakeLock.isHeld()) {
                    wakeLock.acquire(60 * 1000L); // 1 minute
                }
                startVibrating();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mScreenReceiver);
        stopVibrating();
        if (wakeLock.isHeld()) {
            wakeLock.release();
        }
    }

    private void initView() {
        //测试通过
        mTestPass.setOnClickListener(v -> {
            Intent intent = new Intent(VibrationActivity.this, ItemTestActivity.class);
            intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1)); // 获取启动该Activity时传递的ItemId
            intent.putExtra("status", "pass");
            intent.putExtra("check", getIntent().getStringExtra("check"));
            setResult(RESULT_OK , intent);
            finish();
        });
        //测试失败
        mTestFail.setOnClickListener(v -> {
            Intent intent = new Intent(VibrationActivity.this, ItemTestActivity.class);
            intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1)); // 获取启动该Activity时传递的ItemId
            intent.putExtra("status", "fail");
            intent.putExtra("check", getIntent().getStringExtra("check"));
            setResult(RESULT_OK , intent);
            finish();
        });
    }
}